//
//  LearningGlobalTools.swift
//  LearningLanguage
//
//  Created by Rui on 2023/8/15.
//

import UIKit
import Kingfisher

class FJGlobalTools: NSObject{
    static let shared       = FJGlobalTools()
    public var playingId: String = ""
    public var isCalss: Bool = false
    public var reportSel: Bool = false
}

//MARK: - Cache
extension FJGlobalTools {
    
    /// 计算缓存
    func queryCacheSize() -> Double {
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first,
              let fileArray = FileManager.default.subpaths(atPath: cachePath)
        else {return 0}
        var size = 0
        fileArray.forEach {
            let path = cachePath + ("/\($0)")
            if let floder = try? FileManager.default.attributesOfItem(atPath: path) {
                for (key, fileSize) in floder {
                    // 累加文件大小
                    if key == FileAttributeKey.size {
                        size += (fileSize as AnyObject).integerValue
                    }
                }
            }
        }
        let totalCache = Double(size)/1024.00/1024.00
        return totalCache
    }
    
    /// 清理缓存
    func clearCache(_ completion: @escaping (()->Void)) {
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first,
              let fileArray = FileManager.default.subpaths(atPath: cachePath)
        else {return}
        fileArray.forEach {
            let path = cachePath + ("/\($0)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                    let cache = KingfisherManager.shared.cache
                    cache.clearDiskCache()
                    cache.clearMemoryCache()
                    cache.cleanExpiredDiskCache()
                } catch let error {
                    print(error.localizedDescription)
                }
            }
        }
        DispatchQueue.main.async {
            completion()
        }
    }
}
